package com.Cychat.notice.service.impl;

import com.Cychat.commons.config.OssConfig;
import com.Cychat.commons.entity.pojo.Notice;


import com.Cychat.notice.entity.vo.NoticeVO;
import com.Cychat.notice.mapper.NoticeMapper;
import com.Cychat.notice.service.NoticeService;
import com.aliyun.oss.OSS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice> implements NoticeService {
    @Autowired
    private NoticeMapper noticeMapper;
    @Autowired
    private OssConfig ossConfig;
    @Autowired
    private OSS ossClient;

    @Override

    public List<NoticeVO> getAllNotice() {
        List<Notice> notices = noticeMapper.selectList( null);
        // 2. 转换为NoticeVO列表并处理images分割
        return notices.stream()
                .map(notice -> {
                    NoticeVO noticeVO = new NoticeVO();
                    // 复制父类字段（注意：需确保Notice和NoticeVO的字段名一致）
                    BeanUtils.copyProperties(notice, noticeVO);
                    // 分割images为数组
                    noticeVO.splitImages();
                    return noticeVO;
                })
                .collect(Collectors.toList());
    }

    @Override
    public NoticeVO getNoticeById(Integer noticeId) {
        Notice notice = noticeMapper.selectById(noticeId);
        NoticeVO noticeVO = new NoticeVO();
        BeanUtils.copyProperties(notice, noticeVO);
        noticeVO.splitImages();
        return noticeVO;
    }

    @Override
    public String updateAvatar(MultipartFile file) {
        try {
            // 指定文件夹路径，例如: avatars/用户名/文件名
            String folderPath = "post/";

            // 生成唯一文件名
            String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();

            // 完整的对象键（包含文件夹路径）
            String objectName = folderPath + fileName;

            // 上传文件
            ossClient.putObject(ossConfig.getBucketName(), objectName, file.getInputStream());

            // 返回访问URL
            return "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint() + "/" + objectName;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            // 注意：这里不再关闭ossClient，因为它现在是Spring管理的Bean
        }
    }
}